package cn.dansj.common.utils.jdbc.configure;

import cn.dansj.common.processor.meta.WriteToAutoConfiguration;
import cn.dansj.common.utils.jdbc.DBUtils;
import cn.dansj.common.utils.jdbc.jdbcTemplate.JdbcTemplate;
import cn.dansj.common.utils.spring.context.condition.ConditionalOnBean;
import cn.dansj.common.utils.spring.context.condition.ConditionalOnClass;
import cn.dansj.common.utils.spring.context.condition.MatchType;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@WriteToAutoConfiguration
@ConditionalOnClass(value = {DruidDataSource.class, ConfigurationProperties.class}, name = "org.springframework.jdbc.core.JdbcTemplate")
@Configuration
public class DefaultDatasourceConfigure {
    static final String prefix = "spring.datasource";
    private static final Logger logger = LoggerFactory.getLogger(DefaultDatasourceConfigure.class);

    @Bean
    @ConfigurationProperties(prefix = prefix)
    @ConditionalOnBean(matchType = MatchType.Miss)
    public DruidDataSource dataSource() {
        logger.info("default datasource configure ready");
        return DBUtils.createDataSource();
    }

    @Bean
    @ConditionalOnBean(matchType = MatchType.Miss)
    public JdbcTemplate jdbcTemplate(DataSource datasource) {
        logger.info("default jdbcTemplate configure ready");
        return new JdbcTemplate(datasource);
    }
}
